package com.wufeng.controller;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.wufeng.constant.CachePrefix;
import com.wufeng.dto.R;
import com.wufeng.entity.User;
import com.wufeng.service.UserService;
import com.wufeng.service.cache.CacheService;
import com.wufeng.utils.SmsUtil;
import com.wufeng.utils.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.concurrent.TimeUnit;


/**
 * 腾讯云短信服务
 *
 * @author WuFeng
 */
@RestController
@RequestMapping("/sms")
public class TencentSmsController {

    @Autowired
    private SmsUtil smsUtil;

    @Autowired
    private CacheService cacheService;

    @Autowired
    private UserService userService;

    /**
     * 发送验证码
     *
     * @param number 手机号
     * @param prefix 前缀
     * @return
     */
    @GetMapping("/sendMessage")
    public R sendSms(@RequestParam("number") String number, String prefix) {
        //1.生成6位的验证码
        String code = StringUtils.generateCode(6);

        //2.发送短信
        smsUtil.sendSMS(number, code,prefix);

        //3.将手机号和验证码缓存到redis数据库，并设置有效期为1分钟
        String key = "";
        if (prefix == null) {
            key = CachePrefix.REGISTER.getPrefix() + number;
        } else {
            key = prefix + number;
        }

        System.out.println(key);
        cacheService.add(key, code, 60, TimeUnit.SECONDS);

        return R.ok();
    }


    /**
     * 根据用户id发送验证码
     *
     * @param userId
     * @param prefix
     * @return
     */
    @GetMapping("/sendSmsByUserId")
    public R sendSmsByUserId(@RequestParam("userId") Integer userId, String prefix) {
        //1.生成6位的验证码
        String code = StringUtils.generateCode(6);


        User user = userService.getById(userId);
        if (user == null || user.getPhonenumber() == null || "".equals(user.getPhonenumber()) || user.getPhonenumber().length() != 11) {
            return R.error("发送失败");
        }

        String number = user.getPhonenumber();

        //2.发送短信
        smsUtil.sendSMS(number, code,prefix);
        System.out.println("已发送短信");

        //3.将手机号和验证码缓存到redis数据库，并设置有效期为1分钟
        String key = "";
        if (prefix == null) {
            key = CachePrefix.REGISTER.getPrefix() + number;
        } else {
            key = prefix + number;
        }

        System.out.println(key);
        cacheService.add(key, code, 60, TimeUnit.SECONDS);

        return R.ok();
    }

}
